package service.impl;

import dao.RoleDAO;
import dao.RoleFunctionDAO;
import entity.Role;
import entity.RoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.RoleService;

import java.util.Collection;
import java.util.List;

/**
 * Created by asus on 2017/6/17.
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private RoleFunctionDAO roleFunctionDAO;

    /**
     * 保存角色信息，同时保存角色对应的功能
     *
     * @param role
     * @param roleFunctions
     */
    @Override
    public void addRole(Role role, List<RoleFunction> roleFunctions) {
        roleDAO.save(role);
        for (int i = 0; i < roleFunctions.size(); i++) {
            roleFunctions.get(i).setRoleId(role.getId());
        }
        roleFunctionDAO.saveRoleFunction(roleFunctions);
    }

    /**
     * 修改角色信息，同时修改角色对应的功能
     *
     * @param role
     * @param roleFunctions
     */
    @Override
    public void editRole(Role role, List<RoleFunction> roleFunctions) {
        roleDAO.update(role);
        roleFunctionDAO.deleteByRoleId(role.getId());
        for (int i = 0; i < roleFunctions.size(); i++) {
            roleFunctions.get(i).setRoleId(role.getId());
        }
        roleFunctionDAO.saveRoleFunction(roleFunctions);
    }

    /**
     * 分页查询角色信息
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<Role> getRoles(int page, int size) {
        List<Role> roles = (List<Role>) roleDAO.findPage(page, size);
        for (Role role : roles) {
            List<RoleFunction> roleFunctions = roleFunctionDAO.findRoleFunctionsByRoleId(role.getId());
            StringBuilder functionIds = new StringBuilder();
            for (RoleFunction roleFunction : roleFunctions) {
                functionIds.append(roleFunction.getFunctionId()).append(",");
            }
            if (functionIds.length() > 1) {
                role.setFuntionIds(functionIds.deleteCharAt(functionIds.length() - 1).toString());
            }
        }
        return roles;
    }

    /**
     * 根据id删除角色
     *
     * @param roleId
     */
    @Override
    public void deleteRole(Long roleId) {
        roleDAO.deleteById(roleId);
        roleFunctionDAO.deleteByRoleId(roleId);
    }

    /**
     * 根据id集合查询角色信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<Role> getRoles(Collection<Long> ids) {
        return (List<Role>) roleDAO.findByIds(ids);
    }

    /**
     * 根据用户id查询用户功能对应关系
     *
     * @param roleId
     * @return
     */
    @Override
    public List<RoleFunction> getRoleFunction(Long roleId) {
        return roleFunctionDAO.findRoleFunctionsByRoleId(roleId);
    }
}
